package com.swift.violent.mainstay.log.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.swift.violent.mainstay.common.constants.CacheConstants;
import com.swift.violent.mainstay.common.constants.Global;
import com.swift.violent.mainstay.common.util.IpUtil;
import com.swift.violent.mainstay.common.util.ParameterUtil;
import com.swift.violent.mainstay.log.enums.BusinessStatus;
import com.swift.violent.mainstay.log.model.LogBean;
import com.swift.violent.mainstay.log.model.domain.SysOperLog;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 日志同步服务
 * The type Log sync service.
 *
 * @author xuhaifeng
 * @date 2021.1.30 11:26
 */
@Slf4j
@SuppressWarnings("UnusedReturnValue")
public class LogSyncService {

    /**
     * 处理日志
     */
    @SneakyThrows
    public static boolean handleLog(final String apiName, final String logOption, final Object jsonResult, final String handler,
                                    final Throwable exception, final HttpServletRequest request) {
        final LogBean logBean = JSON.parseObject(logOption, LogBean.class);
        final String title = logBean.getTitle();
        final SysOperLog sysOperLog = SysOperLog.builder()
                /* TODO: 返回参数获取 */
                .method(handler)
                .operUrl(request.getRequestURI())
                .operIp(IpUtil.getIpAddr(request))
                .requestMethod(request.getMethod())
                .status(BusinessStatus.SUCCESS.ordinal())
                .operatorType(logBean.getOperatorType().ordinal())
                .businessType(logBean.getBusinessType().ordinal())
                .title(StrUtil.isNotEmpty(title) ? title : apiName)
                .jsonResult(Global.NOT.equals(jsonResult) ? exception.getMessage() : jsonResult)
                .build();
        final String username = request.getHeader(CacheConstants.DETAILS_USERNAME);
        if (StrUtil.isNotEmpty(username)) {
            sysOperLog.setOperName(username);
        }
        if (Objects.nonNull(exception)) {
            sysOperLog.setStatus(BusinessStatus.FAIL.ordinal());
            sysOperLog.setErrorMsg(StrUtil.sub(exception.getMessage(), 0, 2000));
        }
        if (logBean.isSaveRequestData()) {
            final String requestMethod = sysOperLog.getRequestMethod();
            if (HttpMethod.GET.name().equals(requestMethod)) {
                sysOperLog.setOperParam(ParameterUtil.getParameterByFormData(request));
            }
            if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
                sysOperLog.setOperParam(JSON.parseObject(ParameterUtil.getParameterByJson(request)));
            }
        }
        /* TODO: 请求存储日志 */
        log.info(JSON.toJSONString(sysOperLog));
        return true;

    }

}
